package com.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DateConverter implements Converter<String, Date> {
    
    private static final List<String> formarts = new ArrayList<>(4);
    
    static {
        formarts.add("yyyy-MM");
        formarts.add("yyyy-MM-dd");
        formarts.add("yyyy-MM-dd hh:mm");
        formarts.add("yyyy-MM-dd hh:mm:ss");
        formarts.add("HH:mm:ss");
    }
    
    
    @Override
    public Date convert(String s) {
        Date date = null;
        boolean isLong = false;
        if (s == null || s.equals("")) {
            return null;
        }
        String formatter = "";
        if (s.matches("^\\d{4}-\\d{1,2}$")) {
            formatter = formarts.get(0);
        } else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            formatter = formarts.get(1);
        } else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
            formatter = formarts.get(2);
        } else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            formatter = formarts.get(3);
        } else if (s.matches("^\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            formatter = formarts.get(4);
        } else if (s.matches("^[0-9]*$")) {
            isLong = true;
        } else {
            throw new IllegalArgumentException("前台传的日期格式错误 -> '" + s + "'");
        }
        SimpleDateFormat df = new SimpleDateFormat(formatter);
        try {
            if (isLong) {
                date = new Date(Long.parseLong(s));
            } else
                date = df.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}